//
//  WKCardViewController.m
//  Walk
//
//  Created by cesh on 16/8/23.
//  Copyright © 2016年 cesh. All rights reserved.
//

#import "WKCardViewController.h"
#import "CCDraggableContainer.h"


#import "WKSettingViewController.h"
#import "WKChatViewController.h"

#import "WKBubbleViewController.h"
#import "WKSingleViewController.h"
#import "WKMultipleViewController.h"

#import "CustomCardView.h"
#import <SVProgressHUD.h>

static NSUInteger sunTag = 100;
static NSUInteger planetTag = 101;

@interface WKCardViewController ()
<
CCDraggableContainerDataSource,
CCDraggableContainerDelegate,
UICollisionBehaviorDelegate,
UIGestureRecognizerDelegate
>
{
    UIDynamicAnimator *_animator;
    UIDynamicItemBehavior *_dynamicItemBehavior;
    
    NSMutableArray<UIImageView *> *_entity;
    NSArray<NSString *> *_imageNameArray;
    NSArray<NSDictionary *> *_data;
    
    UIImageView *_fireButton;
    UIImageView *_sun;
    UIImageView *_meteor;
    
    NSTimer *_timer;
    CGFloat _space;
    CGFloat _angle;
    NSInteger _count;
}
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIButton *frogBtn;

@property (nonatomic, strong) CCDraggableContainer *container;
@property (nonatomic, strong) NSMutableArray *dataSources;

@property (weak, nonatomic) IBOutlet UIButton *disLikeButton;
@property (weak, nonatomic) IBOutlet UIButton *likeButton;

@property (strong, nonatomic) UIView *radarView;

@property (strong, nonatomic) NSArray *userData;

@property (assign, nonatomic) NSInteger currentCardIndex;

@property (strong, nonatomic) NSURLSessionDataTask *checkSameRequest;
@property (strong, nonatomic) NSURLSessionDataTask *waitForSuccess;

@property (strong, nonatomic) UILabel *scanLabel;
@end

@implementation WKCardViewController

- (IBAction)settingBtn:(id)sender {
    WKSettingViewController *settingVC = [[WKSettingViewController alloc]init];
    [self presentViewController:settingVC animated:YES completion:nil];
}
- (IBAction)chatBtn:(id)sender {
    NSString *status = [[NSUserDefaults standardUserDefaults]objectForKey:@"matchStatus"];
    if ([status isEqualToString:@"3"]) {
        WKChatViewController *chatVC = [[WKChatViewController alloc]init];
        [self presentViewController:chatVC animated:NO completion:nil];
    }
    else {
        //弹出请先匹配成功才能进入聊天室
        [WKPopView showWithType:PopViewTypeNotMatchYet];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WKPopView dismiss];
        });
    }
}
- (IBAction)frogBtn:(id)sender {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    WKBubbleViewController *bubbleVC = [[WKBubbleViewController alloc]init];
    CATransition *anim = [CATransition animation];
    anim.type = @"rippleEffect";
    anim.duration = 1.0;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
    
    [UIApplication sharedApplication].keyWindow.rootViewController = bubbleVC;
}

- (void)like {
    [self likeEvent:nil];
}

- (IBAction)likeEvent:(id)sender {
    //向右滑
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"firstLaunch"]) {
        static BOOL isFirstRight = YES;
        static dispatch_once_t onceToken2;
        dispatch_once(&onceToken2, ^{
            [WKPopView showWithType:PopViewTypeRightScrool];
        });
        isFirstRight = NO;
    }
    
    [self.container removeFormDirection:CCDraggableDirectionRight];
    [self setLikeDislikeBtnStatus];
}
- (void)dislike {
    [self dislikeEvent:nil];
}
- (IBAction)dislikeEvent:(id)sender {
    //向左划
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"firstLaunch"]) {
        static BOOL isFirstLeft = YES;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            [WKPopView showWithType:PopViewTypeLeftScroll];
        });
        isFirstLeft = NO;
    }
    
    [self.container removeFormDirection:CCDraggableDirectionLeft];
    [self setLikeDislikeBtnStatus];
}
- (void)setLikeDislikeBtnStatus {
    self.likeButton.enabled = NO;
    self.disLikeButton.enabled = NO;
    if (self.currentCardIndex != self.userData.count) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.likeButton.enabled = YES;
            self.disLikeButton.enabled = YES;
        });
    }
}
//卡片的UI
- (void)loadUI {
    
    self.container = [[CCDraggableContainer alloc] initWithFrame:CGRectMake(0, 70, CCWidth, CCWidth + 90) style:CCDraggableStyleUpOverlay];
    self.container.delegate = self;
    self.container.dataSource = self;
    [self.view addSubview:self.container];
    
    [self.container reloadData];
}

- (void)cancelRequests {
    [self.checkSameRequest cancel];
    [self.waitForSuccess cancel];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"chatroom"];
    
    self.currentCardIndex = 0;
    
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"firstLaunch"]) {
        static BOOL isFirst = YES;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            // 首次进入的引导界面
            UIImageView *card_guide = [[UIImageView alloc]init];
            card_guide.frame = [UIScreen mainScreen].bounds;
            card_guide.image = [UIImage imageNamed:@"card_guide_0"];
            card_guide.userInteractionEnabled = YES;
            //添加点击删除引导界面的操作
            UITapGestureRecognizer *dismissGuide = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeGuide:)];
            [card_guide addGestureRecognizer:dismissGuide];
            [self.view addSubview:card_guide];
        });
        if (!isFirst) {
            [self createRadar];
            [self waitForMatchSuccess];
        }
        isFirst = NO;
    }
    
    else {
        [self createRadar];
        [self waitForMatchSuccess];
    }
}

- (void)removeGuide:(UITapGestureRecognizer *)tap {
    static int index = 1;
    
    if (index == 4) {
        [tap.view removeFromSuperview];
        [self createRadar];
        [self waitForMatchSuccess];
    }
    UIImageView *card_guide = (UIImageView *)tap.view;
    
    card_guide.image = [UIImage imageNamed:[NSString stringWithFormat:@"card_guide_%i", index]];
    
    index++;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(cardRemove:) name:@"cardDisappear" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(cancelRequests) name:@"cancelRequests" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"cardDisappear" object:nil];
}


- (void)cardRemove:(NSNotification *)noti {
    NSLog(@"%@",noti);
    NSString *handleType = [noti.object isEqualToString:@"left"] ? @"-1" : @"1";
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    NSDictionary *dict = @{
                           @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                           @"myEventID" : [[NSUserDefaults standardUserDefaults]valueForKey:@"eventID"],
                           @"handleType" : handleType,
                           @"eventID" : self.userData[self.currentCardIndex][@"id"]
                           };
    [mgr POST:[NSString stringWithFormat:@"%@Frog/handleLike", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"操作卡片 %@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"操作卡片失败 %@", error);
    }];
    
    self.currentCardIndex++;
}

- (void)waitForMatchSuccess {
    if (self.waitForSuccess != nil) {
        [self.waitForSuccess cancel];
    }
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    NSDictionary *dict = @{
                           @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                           @"myEventID" : [[NSUserDefaults standardUserDefaults]valueForKey:@"eventID"]
                           };
    [mgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    mgr.requestSerializer.timeoutInterval = MAXFLOAT;
    [mgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    self.waitForSuccess = [mgr POST:[NSString stringWithFormat:@"%@Frog/matchSuccessPush",URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"！！！匹配成功 %@", responseObject);
        if ([responseObject[@"state"] isEqualToString:@"FAIL"]) {
            return;
        }
        
        [self.checkSameRequest cancel];
        //排除点击继续招募的时候 又一次进入聊天界面
        [[NSUserDefaults standardUserDefaults]setObject:@"3" forKey:@"matchStatus"];
        NSString *continueAddStatus = responseObject[@"data"][@"continueAddStatus"];
        if (![continueAddStatus isEqualToString:@"1"]) {
            [WKPopView showWithType:PopViewTypeMatchSuccess];
            //记录下环信聊天室的id
            NSDictionary *chatroom = responseObject[@"data"];
            [[NSUserDefaults standardUserDefaults]setObject:chatroom forKey:@"chatroom"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [WKPopView dismiss];
                //进入聊天界面
                [self chatBtn:nil];
            });
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"！！！等待匹配失败 %@", error);
    }];
}

//移除雷达并加载卡片
- (void)loadCard {
    [self.radarView removeFromSuperview];
    
    self.likeButton.enabled = YES;
    self.disLikeButton.enabled = YES;
    [self loadData];
    [self loadUI];
    self.likeButton.hidden = NO;
    self.disLikeButton.hidden = NO;
    CATransition *anim = [CATransition animation];
    anim.type = @"rippleEffect";
    anim.duration = 1.0;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
}
#pragma mark - 雷达
- (void)createRadar {
    
    self.likeButton.hidden = YES;
    self.disLikeButton.hidden = YES;
    
    self.radarView = [[UIView alloc]init];
    self.radarView.size = CGSizeMake(300, 300);
    self.radarView.center = CGPointMake(screenW * 0.5, screenH * 0.5 - 25);
    
    UILabel *scanLabel = [[UILabel alloc]init];
    scanLabel.text = @"正在扫描附近1公里内蛙客...";
    scanLabel.font = [UIFont systemFontOfSize:15.0];
    scanLabel.textColor = [UIColor colorWithRed:0x4a / 255.0 green:0x4a / 255.0 blue:0x4a / 255.0 alpha:1.0];
    scanLabel.size = CGSizeMake(screenW, 50);
    scanLabel.numberOfLines = 0;
    scanLabel.textAlignment = NSTextAlignmentCenter;
    scanLabel.center = CGPointMake(self.radarView.width * 0.5, self.radarView.height + 33);
    self.scanLabel = scanLabel;
    [self.radarView addSubview:scanLabel];
    
    [self.view addSubview:self.radarView];
    
    _entity = [NSMutableArray array];
    _imageNameArray = @[@"default_head", @"image_2", @"image_3", @"image_4", @"image_5", @"image_6"];
    _count = _imageNameArray.count;
    [self createEntity];
    [self createBehavior];
    //开始匹配 (找寻同类匹配)
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    NSLog(@"token %@", [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"]);
    NSLog(@"%@", [[NSUserDefaults standardUserDefaults]valueForKey:@"eventID"]);
    NSDictionary *dict = @{
                           @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                           @"myEventID" : [[NSUserDefaults standardUserDefaults]valueForKey:@"eventID"],
                           @"page" : @"1",
                           @"pagesize" : @"10",
                           @"matchType" : @"1"
                           };
    NSLog(@"%@", dict);
    [mgr POST:[NSString stringWithFormat:@"%@Frog/statrMatching", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"开始匹配（同类）%@", responseObject);
        if ([responseObject[@"state"] isEqualToString:@"FAIL"]) {
            return;
        }
        
        if ([responseObject[@"data"] count] == 0) {
//            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
//            [SVProgressHUD showInfoWithStatus:@"当前附近1公里内没有同类匹配，为您推荐其他活动"];
            scanLabel.text = @"当前附近1公里内没有同类匹配\n为您推荐其他活动";
            //挂起检查同类匹配的链接
            AFHTTPSessionManager *mgrCheckSame = [AFHTTPSessionManager manager];
            mgrCheckSame.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                              @"text/html",
                                                              @"image/jpeg",
                                                              @"image/png",
                                                              @"application/octet-stream",
                                                              @"text/json",
                                                              nil];
            NSDictionary *dictCheckSame = @{
                                    @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                                    @"myEventID" : [[NSUserDefaults standardUserDefaults]valueForKey:@"eventID"]
                                    };
            [mgrCheckSame.requestSerializer willChangeValueForKey:@"timeoutInterval"];
            mgrCheckSame.requestSerializer.timeoutInterval = MAXFLOAT;
            [mgrCheckSame.requestSerializer didChangeValueForKey:@"timeoutInterval"];
            
//            if (self.checkSameRequest != nil) {
//                [self.checkSameRequest cancel];
//            }
            
            self.checkSameRequest = [mgrCheckSame POST:[NSString stringWithFormat:@"%@Frog/haveCommonTypePush", URL] parameters:dictCheckSame progress:^(NSProgress * _Nonnull uploadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSLog(@"获取到新的同类匹配, %@", responseObject);
                if ([responseObject[@"state"] isEqualToString:@"FAIL"]) {
                    return;
                }
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD showInfoWithStatus:@"已检测到同类活动，现为您推送"];
                [self.radarView removeFromSuperview];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    WKCardViewController *cardVC = [[WKCardViewController alloc]init];
                    CATransition *anim = [CATransition animation];
                    anim.type = @"rippleEffect";
                    anim.duration = 1.0;
                    [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
                    [self presentViewController:cardVC animated:NO completion:nil];
                });
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"获取到新的同类匹配 失败 %@", error);
            }];
            

            
            //发送推荐匹配的请求
            AFHTTPSessionManager *mgr2 = [AFHTTPSessionManager manager];
            mgr2.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             @"text/html",
                                                             @"image/jpeg",
                                                             @"image/png",
                                                             @"application/octet-stream",
                                                             @"text/json",
                                                             nil];
            NSDictionary *dict2 = @{
                                   @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                                   @"myEventID" : [[NSUserDefaults standardUserDefaults]valueForKey:@"eventID"],
                                   @"page" : @"1",
                                   @"pagesize" : @"10",
                                   @"matchType" : @"2"
                                   };
            [mgr2 POST:[NSString stringWithFormat:@"%@Frog/statrMatching", URL] parameters:dict2 progress:^(NSProgress * _Nonnull uploadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSLog(@"开始匹配（推荐） %@", responseObject);
                if ([responseObject[@"state"] isEqualToString:@"FAIL"]) {
                    return;
                }
                
                if ([responseObject[@"data"] count] == 0) {
                    //没有推荐的匹配,查找其他的
                    AFHTTPSessionManager *mgr3 = [AFHTTPSessionManager manager];
                    mgr3.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                      @"text/html",
                                                                      @"image/jpeg",
                                                                      @"image/png",
                                                                      @"application/octet-stream",
                                                                      @"text/json",
                                                                      nil];
                    NSDictionary *dict3 = @{
                                            @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                                            @"myEventID" : [[NSUserDefaults standardUserDefaults]valueForKey:@"eventID"],
                                            @"page" : @"1",
                                            @"pagesize" : @"10",
                                            @"matchType" : @"3"
                                            };
                    [mgr3 POST:[NSString stringWithFormat:@"%@Frog/statrMatching", URL] parameters:dict3 progress:^(NSProgress * _Nonnull uploadProgress) {
                    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        NSLog(@"开始匹配（其他）%@", responseObject);
                        if ([responseObject[@"state"] isEqualToString:@"FAIL"]) {
                            return;
                        }
                        
                        /// 当其他匹配也没有数据时，雷达一直转，等待中...
                        if ([responseObject[@"data"] count] == 0) {
//                            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
//                            [SVProgressHUD showInfoWithStatus:@"附近1公里内暂未搜寻到其他活动，请稍等片刻"];
                            scanLabel.text = @"一公里内暂无其他活动\n稍后蛙客会第一时间通知您新的活动";
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [SVProgressHUD dismiss];
//                                [self frogBtn:nil];
                            });
                        }
                        else {
                            [SVProgressHUD dismiss];
                            self.userData = responseObject[@"data"];
                            [self loadCard];
                        }
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        NSLog(@"开始匹配（其他）失败%@", error);
                    }];
                }
                else {
                    [SVProgressHUD dismiss];
                    self.userData = responseObject[@"data"];
                    [self loadCard];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"开始匹配（推荐）失败 %@", error);
            }];
        }
        //找到同类匹配的
        else {
            self.userData = responseObject[@"data"];
            [self loadCard];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"开始匹配(同类)失败%@", error);
    }];

}


- (void)createEntity {
    
    //生成中心图片
    
    _sun = [[UIImageView alloc]init];
    _sun.size = CGSizeMake(50, 50);
    _sun.center = CGPointMake(self.radarView.width * 0.5, self.radarView.height * 0.5);
    _sun.image = [UIImage imageNamed:_imageNameArray.firstObject];
    _sun.layer.cornerRadius = _sun.width / 2;
    _sun.layer.masksToBounds = YES;

    _sun.tag = sunTag;
    [_entity addObject:_sun];
    [self.radarView addSubview:_sun];
    
    CAShapeLayer *sunShadowLayer = [CAShapeLayer layer];
    sunShadowLayer.frame = _sun.frame;
    sunShadowLayer.fillColor = [UIColor orangeColor].CGColor;
    sunShadowLayer.strokeColor = [UIColor clearColor].CGColor;

    [self.radarView.layer addSublayer:sunShadowLayer];
    
    //生成环绕图片
    _space = screenW / 320.0 * 12 ;
    for (int i = 0; i < _count - 1; i++) {
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.position = _sun.center;
        shapeLayer.fillColor = [UIColor clearColor].CGColor;
        shapeLayer.strokeColor = [UIColor colorWithRed:0x4a / 255.0 green:0x4a / 255.0 blue:0x4a / 255.0 alpha:1.0].CGColor;
        shapeLayer.lineWidth = 2;
        [self.radarView.layer addSublayer:shapeLayer];
        
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.size = CGSizeMake(25, 25);
        imageView.center = CGPointMake(CGRectGetMidX(_sun.frame), CGRectGetMaxY(_sun.frame) + CGRectGetWidth(imageView.frame) / 2 + _space + i * (imageView.width * 0.5 + _space));
        
        imageView.image = [UIImage imageNamed:_imageNameArray[i + 1]];
        imageView.layer.cornerRadius = imageView.width / 2;
        imageView.layer.masksToBounds = YES;
        
        imageView.tag = planetTag + i;
        [_entity addObject:imageView];
        [self.radarView addSubview:imageView];
        
        CGFloat radius = CGRectGetMidY(imageView.frame) - CGRectGetMidY(_sun.frame);
        shapeLayer.frame = CGRectMake(0, 0, radius * 2, radius * 2);
        shapeLayer.path = [UIBezierPath bezierPathWithArcCenter:_sun.center radius:radius startAngle:-M_PI endAngle:M_PI clockwise:YES].CGPath;
    }
    
    
    [self.radarView bringSubviewToFront:_sun];
    
}
- (CGFloat)randomWithLength:(CGFloat)range {
    NSUInteger retInt = arc4random() % 20;
    CGFloat ret = retInt / 100.0 * range;
    if (ret == 0) {
        ret = CGFLOAT_MIN;
    }
    return ret;
}

- (void)createBehavior {
    _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.radarView];
    
    //连接行星
    
    UIAttachmentBehavior *sunBehavior = [[UIAttachmentBehavior alloc] initWithItem:_sun attachedToAnchor:_sun.center];
    [sunBehavior setAnchorPoint:_sun.center];
    [_animator addBehavior:sunBehavior];
    
    for (int i = 0; i < _count - 1; i++) {
        UIImageView *imageView = _entity[i + 1];
        UIAttachmentBehavior *attachmentBehavior = [[UIAttachmentBehavior alloc] initWithItem:imageView attachedToAnchor:imageView.center];
        [attachmentBehavior setAnchorPoint:_sun.center];
        [_animator addBehavior:attachmentBehavior];
    }
    
    
    _dynamicItemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:_entity];
    _dynamicItemBehavior.elasticity = 1;//弹性
    _dynamicItemBehavior.resistance = 0;//阻力
    _dynamicItemBehavior.angularResistance = 0;//角阻力
    _dynamicItemBehavior.friction = 0;//摩擦力
    _dynamicItemBehavior.density = 1;//密度
    [_animator addBehavior:_dynamicItemBehavior];
    
    //推动行星
    
    NSMutableArray<UIImageView *> *planets = [_entity mutableCopy];
    for (UIImageView *planet in planets) {
        CGFloat arc = [self randomWithLength:1.0];
        UIPushBehavior *pushBehavior = [[UIPushBehavior alloc] initWithItems:@[planet] mode:UIPushBehaviorModeInstantaneous];
        pushBehavior.pushDirection = CGVectorMake(arc, 0);
        [_animator addBehavior:pushBehavior];
    }
}
//卡片的数据
- (void)loadData {
    NSLog(@"卡片数量 %lu", (unsigned long)self.userData.count);
    _dataSources = [NSMutableArray array];
    
    for (int i = 0; i < self.userData.count; i++) {
        NSDictionary *dict = @{@"image" : self.userData[i][@"user"][@"headerImg"],
                               @"nickname" : self.userData[i][@"user"][@"nickname"],
                               @"birthday" : self.userData[i][@"user"][@"birthday"],
                               @"sex" : self.userData[i][@"user"][@"sex"],
                               @"activity" : self.userData[i][@"event_type"],
                               @"school" : self.userData[i][@"user"][@"school"],
                               @"major" : self.userData[i][@"user"][@"major"],
                               @"moreUsers" : self.userData[i][@"moreUsers"],
                               @"moreUsersCount" : self.userData[i][@"moreUsersCount"]
                               };
        [_dataSources addObject:dict];
    }
}



#pragma mark - CCDraggableContainer DataSource

- (CCDraggableCardView *)draggableContainer:(CCDraggableContainer *)draggableContainer viewForIndex:(NSInteger)index {
    
    CustomCardView *cardView = [[CustomCardView alloc] initWithFrame:draggableContainer.bounds];
    
    NSLog(@"_dataSource[%li] %@", (long)index,_dataSources[index]);
    
    [cardView installData:[_dataSources objectAtIndex:index]];
    
    return cardView;
}

- (NSInteger)numberOfIndexs {
    return _dataSources.count;
}

#pragma mark - CCDraggableContainer Delegate

- (void)draggableContainer:(CCDraggableContainer *)draggableContainer draggableDirection:(CCDraggableDirection)draggableDirection widthRatio:(CGFloat)widthRatio heightRatio:(CGFloat)heightRatio {
    
    CGFloat scale = 1 + ((kBoundaryRatio > fabs(widthRatio) ? fabs(widthRatio) : kBoundaryRatio)) / 4;
    if (draggableDirection == CCDraggableDirectionLeft) {
        self.disLikeButton.transform = CGAffineTransformMakeScale(scale, scale);
    }
    if (draggableDirection == CCDraggableDirectionRight) {
        self.likeButton.transform = CGAffineTransformMakeScale(scale, scale);
    }
    
}

//点击卡片触发事件
- (void)draggableContainer:(CCDraggableContainer *)draggableContainer cardView:(CCDraggableCardView *)cardView didSelectIndex:(NSInteger)didSelectIndex {
    NSLog(@"点击了Tag为%ld的Card", (long)didSelectIndex);
    //获取该卡片对应的数据
    if (cardView.count == 1) {
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
        NSDictionary *dict = @{
                               @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                               @"userID" : self.userData[didSelectIndex][@"user"][@"id"],
                               };
        
        [mgr GET:[NSString stringWithFormat:@"%@Frog/getUserInfo", URL] parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"个人详情 %@",responseObject);
            //根据单人或多人卡片弹出不同的控制器
            
            WKSingleViewController *singleVC = [[WKSingleViewController alloc]init];
            singleVC.isSuperMultiple = NO;
            singleVC.cardVC = self;
            [self presentViewController:singleVC animated:YES completion:nil];
            singleVC.data = responseObject[@"data"];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"个人详情失败 %@", error);
        }];
    }
    else {
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
        NSDictionary *dict = @{
                               @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                               @"eventID" : self.userData[self.currentCardIndex][@"id"],
                               @"page" : @"1",
                               @"pagesize" : @"10"
                               };
        NSLog(@"%@", dict);
        
        [mgr POST:[NSString stringWithFormat:@"%@Frog/getEventMoreUsers", URL] parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"个人详情 %@",responseObject);
            //根据单人或多人卡片弹出不同的控制器
            WKMultipleViewController *multipleVC = [[WKMultipleViewController alloc]init];
            multipleVC.cardVC = self;
            NSArray *others = responseObject[@"data"];
            multipleVC.count = others.count;
            [self presentViewController:multipleVC animated:YES completion:nil];
            multipleVC.data = responseObject[@"data"];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"个人详情失败 %@", error);
        }];
        
    }

}

- (void)draggableContainer:(CCDraggableContainer *)draggableContainer finishedDraggableLastCard:(BOOL)finishedDraggableLastCard {
    self.likeButton.enabled = NO;
    self.disLikeButton.enabled = NO;
    
    [self.container removeFromSuperview];
    [self createRadar];
    self.currentCardIndex = 0;
    
}
@end
